<?php

namespace app\admin\service;

use app\admin\dao\MemberInviteDao;
use app\admin\model\UM as UM;
use app\common\model\MemberInvite;
use think\exception\ValidateException;

/**
 * Class BindService
 * @package app\admin\service
 */
class BindService
{
    // dao
    private MemberInviteDao $memberInviteDao;

    public function __construct(MemberInviteDao $memberInviteDao)
    {
        $this->memberInviteDao = $memberInviteDao;
    }

    /**
     * 绑定邀请关系
     * @param UM $user
     * @param array $params
     * @return  void
     */
    public function add(UM $user, array $params): void
    {
        $memberId = $params['memberId'] ?? null;
        $memberIdInvite = $params['memberIdInvite'] ?? null;

        if (!is_id($memberId)) {
            throw new ValidateException('请选择邀请人');
        }
        if (!is_id($memberIdInvite)) {
            throw new ValidateException('请选择被邀请人');
        }

        $repeat = MemberInvite::where('memberIdInvite', $memberIdInvite)->find();
        if ($repeat) {
            throw new ValidateException('被邀请人已经绑定了' . $repeat->memberId);
        }

        // 插入数据库
        $this->memberInviteDao->insert($memberId, $memberIdInvite, 2);

        // 邀请成功事件
        event('MemberInvited', ['memberIdInvite' => $memberIdInvite]);

    }

}
